"""获取书籍排行榜的爬虫脚本，目前包含：京东、当当网、百道网"""

from typing import Never, Protocol, override
import requests
from parsel import Selector
import pandas as pd
from models.book import Book, BookList, BookRankList


class BookRankingSpider:
    def __init__(self, headers: dict, cookies: dict) -> Never:
        self.headers = headers
        self.cookies = cookies

    def get_month(self):
        pass


class BaiDaoBookRankingSpide(BookRankingSpider):
    type_map = {
        "/images/subject/wx.jpg": "文学类",
        "/images/subject/ys.jpg": "艺术类",
        "/images/subject/sh.jpg": "生活类",
        "/images/subject/se202203.jpg": "少儿原创类",
        "/images/subject/se202203fy.jpg": "少儿翻译类",
        "/images/subject/rw202203.jpg": "人文原创类",
        "/images/subject/rw202203fy.jpg": "人文翻译类",
        "/images/subject/sk.jpg": "社科类",
        "/images/subject/cj.jpg": "财经类",
        "/images/subject/xz2.png": "大众新知类",
        "/images/subject/cj2.png": "教育学习类",
        "/images/subject/zykj.jpg": "专业科技类",
        "/images/subject/ztcb.jpg": "主题出版类",
    }

    def get_month(self, date_str: str):
        """
        Args:
            date_str: 如 202510
        """
        params = {
            "m": date_str,
        }
        response = requests.get(
            "https://www.bookdao.com/subject.aspx",
            params=params,
            cookies=self.cookies,
            headers=self.headers,
        )

        rankings = self.parse(response, date_str)
        return rankings
        # for cat in a.categories_book_list:
        #     for i, book in enumerate(cat.books):
        #         self.df = pd.concat(
        #             [
        #                 self.df,
        #                 pd.DataFrame(
        #                     {
        #                         "标题": book.name,
        #                         "标题链接": book.book_url,
        #                         "排名": i + 1,
        #                         "缩略图": book.img_url,
        #                         "作者": book.author,
        #                         "出版社": book.publish_name,
        #                         "榜单": f"{a.date} 百道好书榜·{cat.type_name}",
        #                     },
        #                     index=[0],
        #                 ),
        #             ],
        #             ignore_index=True,
        #         )

    def get_book_detail(self, book):
        pass

    def parse(self, response, date_str):
        selector = Selector(text=response.text)
        book_types = []
        for book_type in selector.css(".bottom div.wrd_listB"):
            type_name = self.type_map[book_type.xpath("./a/img/@src").get()]
            books = []
            for book in book_type.css("ul li"):
                book_name = book.css("p.wrdb_bkname a::text").get()
                book_url = f'https://www.bookdao.com{book.css("a::attr(href)").get()}'
                author = book.css("p.wrdb_authorame::text").get()
                if not author:
                    print(type_name, book_name)
                    author = ""
                publish_name = book.css("p.wrdb_publishname::text").get()
                book_image_url = book.css("a img::attr(src)").get()
                book_item = Book(
                    site_name="百道网",
                    name=book_name,
                    cover_image_url=book_image_url,
                    detail_url=book_url,
                    author=author,
                    publish_name=publish_name,
                )
                books.append(book_item)
            book_list = BookList(list_name=type_name, books=books)
            book_types.append(book_list)
        return BookRankList(
            rank_date=f"{date_str[:4]}年{date_str[4:]}月", book_ranks=book_types
        )

    def parse_detail(self, response):
        pass




cookies = {
    'ASP.NET_SessionId': 'tsb0trkvdixllhiets2hllzz',
    '__51vcke__JlT1mGOJClC2hNi8': '00e42146-b372-562b-99cb-7e5e299c2f54',
    '__51vuft__JlT1mGOJClC2hNi8': '1762130212576',
    'bookdao.com': 'userid=1865592&username=%e8%83%a1%e6%ad%a3&orgid=1140&orgname=%e6%b3%a8%e5%86%8c%e7%94%a8%e6%88%b7&ispackage=0&UserHobby=0&stype=1&UserSex=True&md5=ef92fd24934aeccce3929f46e6a0f15e',
    '__51uvsct__JlT1mGOJClC2hNi8': '3',
    '__vtins__JlT1mGOJClC2hNi8': '%7B%22sid%22%3A%20%22b58b00ea-04cb-5e04-bb85-81bd04f3b6f3%22%2C%20%22vd%22%3A%203%2C%20%22stt%22%3A%20268406%2C%20%22dr%22%3A%209450%2C%20%22expires%22%3A%201762156859620%2C%20%22ct%22%3A%201762155059620%7D',
}

headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'max-age=0',
    'priority': 'u=0, i',
    'sec-ch-ua': '"Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'none',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    # 'cookie': 'ASP.NET_SessionId=tsb0trkvdixllhiets2hllzz; __51vcke__JlT1mGOJClC2hNi8=00e42146-b372-562b-99cb-7e5e299c2f54; __51vuft__JlT1mGOJClC2hNi8=1762130212576; bookdao.com=userid=1865592&username=%e8%83%a1%e6%ad%a3&orgid=1140&orgname=%e6%b3%a8%e5%86%8c%e7%94%a8%e6%88%b7&ispackage=0&UserHobby=0&stype=1&UserSex=True&md5=ef92fd24934aeccce3929f46e6a0f15e; __51uvsct__JlT1mGOJClC2hNi8=3; __vtins__JlT1mGOJClC2hNi8=%7B%22sid%22%3A%20%22b58b00ea-04cb-5e04-bb85-81bd04f3b6f3%22%2C%20%22vd%22%3A%203%2C%20%22stt%22%3A%20268406%2C%20%22dr%22%3A%209450%2C%20%22expires%22%3A%201762156859620%2C%20%22ct%22%3A%201762155059620%7D',
}
a = BaiDaoBookRankingSpide(headers, cookies)

a.get_month(str(202409))